package com.dhf.framework.system.controller;

import java.io.IOException;
import java.math.BigInteger;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dhf.framework.base.servlet.ValidateCodeServlet;
import com.dhf.framework.base.utils.Coder;
import com.dhf.framework.common.BaseController;
import com.dhf.framework.common.Constants;
import com.dhf.framework.system.entity.RegisterUserBean;
import com.dhf.framework.system.entity.SysUser;
import com.dhf.framework.system.service.SysUserService;

/**
 * 
 * @author HoraceHo
 * @version 1.0
 * 用户注册和登录功能的实现
 */

@Controller
public class LoginController extends BaseController {
    
    @Autowired
    private SysUserService sysUserService;
    
    @RequestMapping(value = "/login")
    public String login(HttpServletRequest request, HttpServletResponse response, Model model) {
        return "login";
    }
    
    
    /**
     * 用户登录
     * @return
     * @throws Exception
     */
   @RequestMapping("/loginIn")
   public ModelAndView login(SysUser sysUser,HttpServletRequest request, RedirectAttributes redirectAttributes) throws Exception{
       String checkCode = ((String) request.getSession().getAttribute(ValidateCodeServlet.VALIDATE_CODE)).toUpperCase() ;
       String inputCode = request.getParameter(ValidateCodeServlet.VALIDATE_CODE).toUpperCase();
       
       if(!checkCode.equals(inputCode)){
           this.addMessage(redirectAttributes, "请输入正确的验证码");
           return new ModelAndView( "redirect:/login.do" );
       }
       
       Boolean a=this.sysUserService.login(sysUser);
       if(a==true){
    	   SysUser searchEntity=new SysUser();
    	   searchEntity.setLoginName(sysUser.getLoginName());
    	   List<SysUser> list=this.sysUserService.query(searchEntity);
           request.getSession().setAttribute(Constants.SESSION_USER_KEY,list.get(0));
           this.addMessage(redirectAttributes, "登录成功");
           return new ModelAndView( "redirect:/" );
       }else{
           this.addMessage(redirectAttributes, "账号或密码不正确");
           return new ModelAndView( "redirect:/login.do" );
       }
       
   }
   
   @RequestMapping("/loginOut")
   public void loginOut(HttpServletRequest request, HttpServletResponse response) throws IOException{
       request.getSession().invalidate();
       response.sendRedirect("login.do");
   }
   
   /**
	 * 跳转注册页面
	 * @return
	 */
	@RequestMapping("/register")
	public String register(){
	    return "register";
	}
	
	/**
	 * 保存注册信息
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/registerSave")
	@ResponseBody
	public Map<String, String> registerSave(RegisterUserBean registerUserBean,HttpServletRequest request, HttpServletResponse response) throws Exception{
		String checkCode = (String) request.getSession().getAttribute(ValidateCodeServlet.VALIDATE_CODE) ;
		Map<String, String> map= new HashMap<String,String>();
		if(!registerUserBean.getCheckcode().toUpperCase().equals(checkCode.toUpperCase())){
			map.put("info","验证码错误");
			map.put("key","checkcode");
			map.put("result","faile");
			return map;
		}
		SysUser searchEntity=new SysUser();
		searchEntity.setName(registerUserBean.getUserName());
		List<SysUser> user= this.sysUserService.query(searchEntity) ;
       if(!user.isEmpty()){
	       	map.put("key","userName");
	       	map.put("info", "注册用户已存在！！");
	       	map.put("result","faile");
	       	return map;
       }
       
       SysUser saveEntity=new SysUser();
       saveEntity.setCreateDate(new Date());
       saveEntity.setLoginName(registerUserBean.getUserName());
       saveEntity.setName(registerUserBean.getUserName());
       String pword=registerUserBean.getPassword();
		if(StringUtils.isNotEmpty(pword)){
			String password=new BigInteger(Coder.encryptHMAC(pword.getBytes(), pword)).toString(16);
			saveEntity.setPassword(password);
		}
		saveEntity.setEmail(registerUserBean.getEmail());
		if(registerUserBean.validate()){
			this.sysUserService.add(saveEntity);
			map.put("result", "success");
		}else{
			map=registerUserBean.getErrors();
			map.put("result"   ,"faile");
		}
		
		return map;
	}
	
	 /**
	  * 跳转到登录页面
	  * @return
	  */
	@RequestMapping("/message")
	public String message(){
	    return "message";
	} 
	
	@RequestMapping(value = "/personInfo")
	@ResponseBody
	public SysUser personInfo(){
		SysUser user= getUser();
		return this.sysUserService.get( user.getId() ) ;
	}
	
	
	@RequestMapping(value = "/modifyPassWord")
	@ResponseBody
	public String modifyPassWord(HttpServletRequest request, String password) throws Exception{
		if(StringUtils.isNotEmpty(password)){
			SysUser sysUser=new SysUser();
			String pwd=new BigInteger(Coder.encryptHMAC(password.getBytes(),password)).toString(16);
			sysUser.setId(getUser().getId());
			sysUser.setPassword(pwd);
	        sysUser.setUpdateBy(getUser().getName());
	        sysUser.setUpdateDate(new Date());
			this.sysUserService.update( sysUser );
			return "修改密码成功";
		}else{
			return"密码不能为空";
		}
	}

}
